import {_decorator, Component, Node, TiledMap, UITransform, Vec2, Vec3} from 'cc';
import {GridSystemManage} from "db://assets/script/modules/GridSystemManage";
import {GameManager} from "db://assets/script/modules/GameManager";
import {SceneManager} from "db://assets/script/modules/SceneManager";

const {ccclass, property} = _decorator;

@ccclass('MapController')
export class MapController extends Component {

    uit: UITransform
    playerNode: Node
    gameCameraNode: Node
    tiledMap: TiledMap;

    start() {
        this.uit = this.node.getComponent(UITransform)
        this.playerNode = GameManager.playerNode
        this.gameCameraNode = GameManager.gameCameraNode
        this.tiledMap = this.getComponent(TiledMap)
        // 初始化网格系统
        GridSystemManage.initGrid(this.getComponent(TiledMap))
        // 初始化人物坐标
        this.initPlayerPos()

        // 取消加载
        SceneManager.hiddenLoading()
    }

    onDestroy() {

    }

    initPlayerPos() {
        // 获取 Tiled 地图属性
        const {dx, dy} = this.tiledMap.getProperties();
        const {width: sizeWidth, height: sizeHeight} = this.tiledMap.getTileSize();
        // 理论上计算为结果必为整数
        const calcX = sizeWidth * (Number(dx) || 0) / GridSystemManage.gridSize
        const calcY = sizeHeight * (Number(dy) || 0) / GridSystemManage.gridSize
        this.playerNode.setPosition(GridSystemManage.gridPosToNodePos(new Vec2(calcX, calcY)));
        // todo 相机位置与玩家位置可能 不重合
        this.gameCameraNode.setPosition(this.playerNode.position.clone());
        this.node.setPosition(Vec3.ZERO)
    }

}
